//
//  LoginViewController.m
//  jiyujiaProgram
//
//  Created by 中良 赵 on 15/10/13.
//  Copyright (c) 2015年 中良 赵. All rights reserved.
//

#import "LoginViewController.h"
#import "TabBarViewController.h"
#import "MainTabViewController.h"
#import "Common.h"
#import "AppDelegate.h"

#import "RegiterViewController.h"
#import "PWDViewController.h"

#import <CoreLocation/CoreLocation.h>
#import "EaseMob.h"

@interface LoginViewController () <CLLocationManagerDelegate,UITextFieldDelegate>

@end

@implementation LoginViewController
{
    MemberModel *_memberModel;
    TeacherModel *_teacherModel;
    CLLocationManager *_locationManager;
    NSString *_lat;
    NSString *_lng;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationController.navigationBarHidden=YES;
    [self creatLocationManager];
}


- (void)viewWillAppear:(BOOL)animated
{
    [_locationManager startUpdatingLocation];
    UserInfoManager *userInfo = [UserInfoManager sharedUserInfoManager];
    [userInfo loadUserInfoFromSanbox];
    self.userTextField.text = userInfo.user;
    self.passwordTextField.text = userInfo.password;
}


- (void)creatLocationManager
{
    _locationManager = [[CLLocationManager alloc] init];
    _locationManager.delegate = self;
    _locationManager.desiredAccuracy=kCLLocationAccuracyBest;
    
    if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusNotDetermined){
        [_locationManager requestWhenInUseAuthorization];
    }
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8) {
        [_locationManager requestWhenInUseAuthorization];
    }
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9) {
        _locationManager.allowsBackgroundLocationUpdates = NO;
    }
}


- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    for (CLLocation *userLocation in locations) {
        if (_lat.length <1 &&_lng.length < 1) {
            _lat = [NSString stringWithFormat:@"%f",userLocation.coordinate.latitude];
            _lng = [NSString stringWithFormat:@"%f",userLocation.coordinate.longitude];
        }else{
            UserInfoManager *userInfo = [UserInfoManager sharedUserInfoManager];
            userInfo.lat = _lat;
            userInfo.lng = _lng;
            [_locationManager stopUpdatingLocation];
        }
        NSLog(@"***CLLOCATION***%@***",userLocation);
    }
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.userTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


//学生
//    MainTabViewController* _mainTabBarVC = [[MainTabViewController alloc] init];
//    UINavigationController *navc = [[UINavigationController alloc] initWithRootViewController:_mainTabBarVC];
//    [APPDELEGATE window].rootViewController = navc;
//    navc.navigationBarHidden = YES;



//教师
//    TabBarViewController *tabBar = [[TabBarViewController alloc] init];
//    [APPDELEGATE window].rootViewController = tabBar;
//    [APPDELEGATE window].backgroundColor = ECCOLOR(255, 255, 255, 1);
//    [[APPDELEGATE window] makeKeyAndVisible];


- (IBAction)loginClick:(id)sender
{
    [self.userTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];
    UIButton *btn=(UIButton*)sender;
    if (_lat.length >0 &&_lng.length > 0) {
        NSDictionary *param = @{
                                @"mobile":self.userTextField.text,
                                @"password":self.passwordTextField.text,
                                @"member_type":[NSString stringWithFormat:@"%d",btn.tag],
                                @"diver_token":[[[UIDevice currentDevice] identifierForVendor] UUIDString],
                                @"lng":_lng,
                                @"lat":_lat,
                                };
        UserInfoManager *userInfo = [UserInfoManager sharedUserInfoManager];
        [[HttpManager defaultManager] postRequestToUrl:RequestURL(LOGIN) params:param complete:^(BOOL successed, NSDictionary *result) {
            if (successed) {
                
                _memberModel = [[MemberModel alloc] init];
                _memberModel = [MemberModel objectWithKeyValues:result];
                userInfo.memberModel = _memberModel;
                userInfo.user = self.userTextField.text;
                userInfo.password = self.passwordTextField.text;
                userInfo.autoLogin = YES;
                if ([_memberModel.errCode integerValue] == 200) {
                    if ([_memberModel.member_type integerValue] == 2) {

                        [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:self.userTextField.text password:self.userTextField.text completion:^(NSDictionary *loginInfo, EMError *error) {
                            if (!error && loginInfo) {
                                [[EaseMob sharedInstance].chatManager setIsAutoLoginEnabled:YES];
                                NSLog(@"登陆成功%@",loginInfo);
                                NSLog(@"学生登陆");
                                [userInfo saveUserInfoToSanbox];
                                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@YES];
//                                MainTabViewController* _mainTabBarVC = [[MainTabViewController alloc] init];
//                                UINavigationController *navc = [[UINavigationController alloc] initWithRootViewController:_mainTabBarVC];
//                                [APPDELEGATE window].rootViewController = navc;
//                                navc.navigationBarHidden = YES;
                            }else{
                                NSLog(@"环信登录失败%@",error);
                            }
                        } onQueue:nil];
                        
                    }else{
                        [self loadTeacherInfo];
                    }
                }else{
                    SHOW_ALERT(@"提示", _memberModel.errMsg, @"好的", nil, nil);
                }
            }
        }];
    }else{
        SHOW_ALERT(@"提示", @"请等待定位，再登录", @"确定", nil, nil);
    }
}


- (void)loadTeacherInfo
{
    NSDictionary *param = @{
                            @"member_Id":_memberModel.member_Id,
                            };
    UserInfoManager *userInfo = [UserInfoManager sharedUserInfoManager];

    [[HttpManager defaultManager] postRequestToUrl:RequestURL(MINEINFO) params:param complete:^(BOOL successed, NSDictionary *result) {
        if (successed) {
            _teacherModel = [[TeacherModel alloc] init];
            _teacherModel = [TeacherModel objectWithKeyValues:result];
            userInfo.teacherModel = _teacherModel;
            if ([_teacherModel.errCode integerValue] == 200) {
                
                [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:self.userTextField.text password:self.userTextField.text completion:^(NSDictionary *loginInfo, EMError *error) {
                    if (!error && loginInfo) {
                        [[EaseMob sharedInstance].chatManager setIsAutoLoginEnabled:YES];
                        NSLog(@"登陆成功%@",loginInfo);
                        NSLog(@"教师登陆");
                        [userInfo saveUserInfoToSanbox];
                        [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@YES];
//                        TabBarViewController *tabBar = [[TabBarViewController alloc] init];
//                        [APPDELEGATE window].rootViewController = tabBar;
//                        [APPDELEGATE window].backgroundColor = ECCOLOR(255, 255, 255, 1);
//                        [[APPDELEGATE window] makeKeyAndVisible];
                    }else{
                        NSLog(@"环信登录失败%@",error);
                    }
                } onQueue:nil];

            }
        }
    }];
}

- (IBAction)forgetClick:(id)sender
{
    [self.userTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];

    PWDViewController *vc = [[PWDViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}


- (IBAction)registerClick:(id)sender
{
    [self.userTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];
    
    RegiterViewController *vc = [[RegiterViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}


@end
